import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import constants from '@/utils/constants'
import RSAEncrypt from '@/utils/common/RSAEncrypt'
import ElementUI from 'element-ui'
import { Message, Loading, MessageBox } from 'element-ui'
let loadingInstance = null
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API : window.g.baseURL,
  timeout: 1000 * 60
})

service.interceptors.request.use(
  config => {
    var loading = true
    if (config.method === 'get') {
      if (config.params != null) {
        if (config.params.loading != null) {
          loading = config.params.loading
        }
      }
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
    if (config.method === 'post') {
      if (config.data != null) {
        if (config.data instanceof FormData) {
          if (config.data.has('loading')) {
            loading = config.data.get('loading')
          }
        }
        if (config.data.loading != null) {
          loading = config.data.loading
        }
      }
    }
    if (loading) {
      loadingInstance = Loading.service({
        fullscreen: true,
        text: '正在请求中...',
        customClass: 'common-loading'
      })
    }
    if (store.getters.token) {
      config.headers['Access-Token'] = getToken()
    }
    config.headers['ProjectsId'] = constants.PROJECTS_ID
    config.headers['App-Id'] = constants.APP_ID
    config.headers['App-Key'] = constants.APP_KEY
    config.headers['Sign'] = RSAEncrypt.paramSign(config)
    return config
  },
  error => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    console.log(response)

    const res = response.data
    if (loadingInstance) {
      loadingInstance.close()
    }
    if (res instanceof ArrayBuffer) {
      var resultBufferString = String.fromCharCode.apply(null, new Uint8Array(res))
      if (resultBufferString.toLocaleLowerCase().indexOf('png') > -1 || resultBufferString.toLocaleLowerCase().indexOf('jfif') > -1) {
        return res
      } else {
        resultBufferString = decodeURIComponent(escape(resultBufferString))
        resultBufferString = JSON.parse(resultBufferString)
        Message({
          message: resultBufferString.data == null ? resultBufferString.message : resultBufferString.data,
          type: 'warning',
          duration: 5 * 1000
        })
      }
    } else if (res instanceof Blob) {
      return handleBlob(response)
    } else {
      if (response.config.url.indexOf('/actuator/') > -1) {
        return res
      }
      if (res.code !== 200) {
        if (res.code === 500) {
          if (res.data.requestId) {
            ElementUI.Notification({
              type: 'error',
              title: '系统异常',
              dangerouslyUseHTMLString: true,
              duration: 10 * 1000,
              message: `<div>
                  错误代码:<m style="color:red">【${res.data.errorCode}】</m><br>
                  请求码:<m style="color:red">【${res.data.requestId}】</m><br>
                  错误描述:<m style="color:red">【${res.data.errorMessage}】${res.data.errorLocalizedMessage}</m><br>
                  <br>备注:<m style="font-style: italic;">请将请求码发送给管理员排查错误!您的反馈将是我们不断进步的动力!</m><br>
                </div>`
            })
          } else {
            Message({
              message: res.data == null ? res.message : res.data,
              type: 'error',
              duration: 5 * 1000
            })
          }
        } else if (res.code === 501) {
          var html = ''
          var data = res.data
          for (var item in data) {
            html += `【${item}】<m style="color:red">${data[item]}</m><br>`
          }
          ElementUI.Notification({
            type: 'warning',
            title: res.message,
            dangerouslyUseHTMLString: true,
            duration: 10 * 1000,
            message: `<div>${html}</div>`
          })
        } else if (res.code === 506003) {
          MessageBox.alert('登录状态已过期需重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
            store.dispatch('removeToken').then(() => {
              location.href = '/#/dashboard'
              window.location.reload()
            })
          }).catch(() => {
          })
        } else {
          Message({
            message: res.data == null ? res.message : res.data,
            type: 'warning',
            duration: 5 * 1000
          })
        }

        return Promise.reject(res)
      } else {
        return res.data
      }
    }
  },
  error => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    console.error('err', error)
    Message({
      message: error.message === 'Network Error' ? '抱歉,服务忙,请稍后重试~' : error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
function handleBlob(response) {
  var res = response.data
  console.log(res)
  if (res.type === 'application/json') {
    const reader = new FileReader()
    reader.addEventListener('loadend', function() {
      var json = JSON.parse(reader.result)
      if (!json.success) {
        Message({
          message: json.data == null ? json.message : json.data,
          type: 'warning',
          duration: 5 * 1000
        })
      }
    })
    reader.readAsText(res, 'UTF-8')
    return Promise.reject(res)
  } else {
    return res
  }
}

service.get = (url, params = {}) => {
  return service({
    method: 'GET',
    url: url,
    params: params
  })
}
service.post = (url, params = {}) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}
service.pictureStream = (url, params) => {
  return service({
    method: 'GET',
    url: url,
    params: params,
    responseType: 'arraybuffer'
  })
}
/**
 * 文件下载
 */
service.downloadFile = (url, params) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

/**
 * 文件上传
 */
service.uploadFile = (url, params) => {
  return service({
    method: 'POST',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export default service
